package com.etooling.framework.filter;

import com.alibaba.fastjson.JSON;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.WebUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 后台系统身份验证拦截器
 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        if ("OPTIONS".equals(request.getMethod().toUpperCase()) || uri.indexOf("upload") > -1 || uri.contains("upload")||uri.contains("Print")||uri.contains("showHtml")||uri.contains("image")
                || uri.contains("/scanner/login") || uri.contains("/scanner/MobileLogin") ||uri.contains("/register")||uri.contains("/getMobileVerifyCode")) {
            return true;
        }
        else if (WebUtils.getSessionValue(request, WebUtils.LOGIN_USER_KEY) == null) {
            response.sendRedirect(request.getContextPath() + "/toReLogin");
            PrintWriter out = null;
            ReplyObj ro = new ReplyObj();
            ro.setMsg("登录超时，请重新登录");
            ro.setCode(407);
            String value = JSON.toJSONString(ro);

            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            //System.out.println(value);
            out = response.getWriter();
            out.write(value.toString());
            out.flush();
            System.out.println(uri + ",被拦截");
            return false;//return false 不放行，拦截住
        } else {
            return true;
        }
    }
}
